<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'design:negoti:pmNegotiation:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmNegotiationMaterialList>
        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2"
          @click="handlePmNegotiationMaterialAdd2"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>

        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2 ml-2"
          @click="handlePmNegotiationMaterialAdd('1')"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择') }}
        </a-button>
        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2 ml-2"
          @click="handleImport('1')"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <BasicTable
          @register="registerPmNegotiationMaterialTable"
          @row-click="handlePmNegotiationMaterialRowClick"
        />
      </template>

      <template #pmNegotiationMaterialListReduce>
        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2"
          @click="handlePmNegotiationMaterialAdd2Jx"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2 ml-2"
          @click="handlePmNegotiationMaterialAdd('2')"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择') }}
        </a-button>
        <a-button
          v-if="
            record.status == '9' || record.status == '6' || record.status == '5' || !record.status
              ? true
              : false
          "
          class="mb-2 ml-2"
          @click="handleImport('2')"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <BasicTable
          @register="registerPmNegotiationMaterialTableJx"
          @row-click="handlePmNegotiationMaterialRowClickJx"
        />
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_Design_PmNegotiation"
        completeText="提交"
        :loading="loadingRef"
        :auth="'design:negoti:pmNegotiation:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>

    <ListSelect
      ref="qsdlsit"
      v-show="false"
      selectType="materialSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
  <FormImport @register="registerImportModal" @success="handleSuccessFormImport" />
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsDesignNegotiPmNegotiationForm',
  });
</script>
<script lang="ts" setup>
  import FormImport from './formImport.vue';
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmNegotiation,
    pmNegotiationSave,
    pmNegotiationForm,
  } from '/@/api/design/negoti/pmNegotiation';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';
  import { useModal } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n('design.negoti.pmNegotiation');
  const { showMessage } = useMessage();
  const record = ref<PmNegotiation>({} as PmNegotiation);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增洽商单') : t('编辑洽商单'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let qsdlsit = ref<any>('');
  let materialFlag = ref<any>('1'); //增 1  减 2
  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('申请信息'),
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('工程名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: { treeOper: '15' },
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            pcode: e,
          };
          let arr = await pmNegotiationMaterialTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            await pmNegotiationMaterialTable.deleteTableDataRecord(item);
          });

          let arrJx = await pmNegotiationMaterialTableJx.getDataSource();
          let arrNewJx = [...arrJx];
          arrNewJx.forEach(async (item, index) => {
            await pmNegotiationMaterialTableJx.deleteTableDataRecord(item);
          });
        },
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    // {
    //   label: t('工程编码'),
    //   field: 'projectno',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 50,
    //     disabled: true,
    //   },
    //   dynamicDisabled: true,
    //   required: true,
    // },
    {
      label: t('工程编码'),
      field: 'projectno1',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('施工员'),
      field: 'pmZone.leaderUser.userName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('涉及水表'),
      field: 'isInvolvewatermeter',
      component: 'Switch',
      componentProps: {
        maxlength: 50,
      },
    },
    {
      label: t('变更类型'),
      field: 'designchangereasonid',
      component: 'Select',
      componentProps: {
        dictType: 'zf_designChg_reson_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('佐证资料（非洽商单）'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmNegotiationDesign_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
      itemProps: { validateTrigger: 'blur' },
      // dynamicDisabled: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('变更原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      required: true,
    },
    {
      label: t('材料增项'),
      field: 'clzx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      // label: t('洽商单材料增减'),
      field: 'pmNegotiationMaterialList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmNegotiationMaterialList',
    },
    {
      label: t('材料减项'),
      field: 'cljx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      // label: t('洽商单材料增减'),
      field: 'pmNegotiationMaterialListReduce',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmNegotiationMaterialListReduce',
    },

    {
      label: t('确认信息'),
      field: 'qrxx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('发出时间'),
      field: 'sendDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('发出人编码'),
      field: 'createBy',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },

    {
      label: t('驳回时间'),
      field: 'backResultDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        placeholder: '',
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('驳回人'),
      field: 'backResultPerson',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('驳回原因'),
      field: 'backResult',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('接口错误信息'),
      field: 'errorContent',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('审核结果'),
      field: 'checkResult',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('调整类型'),
      field: 'ctype',
      component: 'Select',
      componentProps: {
        dictType: 'zf_mat_modify_type',
        allowClear: true,
      },
      show: false,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue, updateSchema }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });

  const [registerPmNegotiationMaterialTable, pmNegotiationMaterialTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmNegotiationMaterialDelete.bind(this, record1),
          },
          auth: 'design:negoti:pmNegotiation:edit',
          ifShow: () =>
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? true
              : false,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerPmNegotiationMaterialTableJx, pmNegotiationMaterialTableJx] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmNegotiationMaterialDeleteJx.bind(this, record1),
          },
          auth: 'design:negoti:pmNegotiation:edit',
          ifShow: () =>
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? true
              : false,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmNegotiationMaterialTableData(_res: Recordable) {
    let columns = [
      {
        title: t('调整类型'),
        dataIndex: 'ctype',
        width: 130,
        align: 'center',
        dictType: 'zf_mat_modify_type',
        ifShow: false,
      },
      {
        title: t('材料编码'),
        dataIndex: 'mcode',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('材料名称'),
        dataIndex: 'mname',
        width: 200,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('规格型号'),
        dataIndex: 'mstd',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('单位'),
        dataIndex: 'munit',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
    ];
    await pmNegotiationMaterialTable.setColumns(columns);
    await pmNegotiationMaterialTableJx.setColumns(columns);
    let arr1 = record.value.pmNegotiationMaterialList.filter((item) => {
      return item.ctype == '1';
    });
    let arr2 = record.value.pmNegotiationMaterialList.filter((item) => {
      return item.ctype == '2';
    });
    pmNegotiationMaterialTable.setTableData(arr1 || []);
    pmNegotiationMaterialTableJx.setTableData(arr2 || []);
  }

  function handlePmNegotiationMaterialRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmNegotiationMaterialRowClickJx(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmNegotiationMaterialAdd2() {
    pmNegotiationMaterialTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      ctype: '1',
    });
  }
  function handlePmNegotiationMaterialAdd2Jx() {
    pmNegotiationMaterialTableJx.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      ctype: '2',
    });
  }

  function handlePmNegotiationMaterialAdd(flag) {
    materialFlag.value = flag;
    if (!getFieldsValue().projectno) {
      showMessage('请先选择工程名称！');
      return;
    }
    listSelectRef.value = [];
    qsdlsit.value.handleInputClick();
  }

  function handlePmNegotiationMaterialDelete(record: Recordable) {
    pmNegotiationMaterialTable.deleteTableDataRecord(record);
  }
  function handlePmNegotiationMaterialDeleteJx(record: Recordable) {
    pmNegotiationMaterialTableJx.deleteTableDataRecord(record);
  }
  const [registerImportModal, { openModal: importModal }] = useModal();
  function handleImport(materialFlag) {
    if (!getFieldsValue().projectno) {
      showMessage('请先选择工程名称！');
      return;
    }
    importModal(true, { materialFlag: materialFlag });
  }

  async function getPmNegotiationMaterialList() {
    let pmNegotiationMaterialListValid = true;
    let pmNegotiationMaterialList: Recordable[] = [];
    for (const record of pmNegotiationMaterialTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmNegotiationMaterialListValid = false;
      }
      pmNegotiationMaterialList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmNegotiationMaterialTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmNegotiationMaterialList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmNegotiationMaterialListValid) {
      throw { errorFields: [{ name: ['pmNegotiationMaterialList'] }] };
    }
    return pmNegotiationMaterialList;
  }

  async function getPmNegotiationMaterialListJx() {
    let pmNegotiationMaterialListValid = true;
    let pmNegotiationMaterialList: Recordable[] = [];
    for (const record of pmNegotiationMaterialTableJx.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmNegotiationMaterialListValid = false;
      }
      pmNegotiationMaterialList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmNegotiationMaterialTableJx.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmNegotiationMaterialList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmNegotiationMaterialListValid) {
      throw { errorFields: [{ name: ['pmNegotiationMaterialList'] }] };
    }
    return pmNegotiationMaterialList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmNegotiationForm(data);
    record.value = (res.pmNegotiation || {}) as PmNegotiation;
    record.value.__t = new Date().getTime();
    record.value.projectno1 = record.value.projectno;
    record.value.isInvolvewatermeter = record.value.isInvolvewatermeter == 'true' ? true : false;
    queryParams.value = {
      pcode: record.value.projectno,
    };
    setFieldsValue(record.value);
    const notEditField = [
      {
        field: 'projectno',
        fieldLabel: 'projectname',
        componentProps: {
          //disabled: record.value.status == '9' || !record.value.status ? false : true,
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'isInvolvewatermeter',
        componentProps: {
          disabled:
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? false
              : true,
        },
      },
      {
        field: 'designchangereasonid',
        componentProps: {
          disabled:
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? false
              : true,
        },
      },
      {
        field: 'remarks',
        componentProps: {
          disabled:
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? false
              : true,
        },
      },
      {
        field: 'dataMap',
        componentProps: {
          disabled:
            record.value.status == '9' ||
            record.value.status == '6' ||
            record.value.status == '5' ||
            !record.value.status
              ? false
              : true,
        },
      },
    ];
    updateSchema(notEditField);
    setPmNegotiationMaterialTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handSelect(selectData) {
    if (materialFlag.value == '1') {
      let arr = await pmNegotiationMaterialTable.getDataSource();
      selectData.forEach((item) => {
        console.log(item, 'item===');
        let flag = true;
        arr.forEach((res) => {
          if (res.mcode == item.mcode) {
            flag = false;
          }
        });
        if (flag) {
          pmNegotiationMaterialTable.insertTableDataRecord({
            ...item,
            // id: new Date().getTime() + item.id,
            editable: true,
            isNewRecord: true,
            projectno: item.pcode,
            munit: item.unit,
            iqty: item.num,
            ctype: '1',
          });
        }
      });
    } else {
      let arr = await pmNegotiationMaterialTableJx.getDataSource();
      selectData.forEach((item) => {
        let flag = true;
        arr.forEach((res) => {
          if (res.mcode == item.mcode) {
            flag = false;
          }
        });
        if (flag) {
          pmNegotiationMaterialTableJx.insertTableDataRecord({
            ...item,
            // id: new Date().getTime() + item.id,
            editable: true,
            isNewRecord: true,
            projectno: item.pcode,
            munit: item.unit,
            iqty: item.num,
            ctype: '2',
          });
        }
      });
    }
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log('status', data.status);
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      data.qsType = '1';
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      let arr1 = await getPmNegotiationMaterialList();
      let arr2 = await getPmNegotiationMaterialListJx();
      data.pmNegotiationMaterialList = [...arr1, ...arr2];
      // console.log('submit', params, data, record);
      const res = await pmNegotiationSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      record.value.status = '';
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
  async function handleSuccessFormImport(data) {
    // 接受子组件传过来的数据
    // console.log(data,'data====');
    data.forEach((item) => {
      if (item.ctype == '1') {
        pmNegotiationMaterialTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          munit: item.unit,
          iqty: item.num,
          ctype: '1',
        });
      } else if (item.ctype == '2') {
        pmNegotiationMaterialTableJx.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          munit: item.unit,
          iqty: item.num,
          ctype: '2',
        });
      }
    });
  }
</script>
